<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/2/13
 * Time: 15:37
 */

namespace app\admin\controller;

use think\Db;

class Logistics extends Main
{

    /**
     * 物流信息列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (isession('user_id') != 1) {
            $where['status'] = 1;
        }
        $where['raw'] = 1;
        $data = Db::name('logistics')
            ->where($where)
            ->order('id asc')
            ->paginate(15);
        $list = $data->all();

        if (isession('user_id') != 1) {
            checkArr($list) && $list = arrayCombine($list, 'id');

            $where1['raw'] = 2;
            $logcom = Db::name('logistics')->field('id,status,pid')->where($where1)->select();

            if (checkArr($logcom)) {
                foreach ($logcom as $value) {
                    isset($list[$value['pid']]) && $list[$value['pid']]['status'] = $value['status'];
                }
            }
        }

        $this->assign('list', $list);
        $this->assign('data', $data);
        return $this->fetch('index');
    }

    /**
     * 添加物流信息
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if (post()) {
            $data = post();
            $data['name'] = trim($data['name']);
            //检测是否存在
            $res = DB::name('logistics')->where('name', $data['name'])->find();
            if (checkArr($res)) {
                $this->error("该物流已存在");
            }
            $data['timestamp'] = time();
            DB::name('logistics')->insert($data);
            $this->success("添加成功");
        } else {
            return $this->fetch('add');
        }
    }

    /**
     * 更新物流信息
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit($id)
    {
        if (post()) {
            $data = post();
            $data['name'] = trim($data['name']);
            $data['manual'] = isset($data['manual']) ? $data['manual'] : 2;
            //检测是否存在
            $where['name'] = $data['name'];
            $where['raw'] = 1;
            $where['id'] = ['neq', $data['id']];
            $res = DB::name('logistics')->where($where)->find();
            if (checkArr($res)) {
                $this->error("该物流已存在");
            }

            unset($data['id']);
            DB::name('logistics')->where('id', post('id'))->update($data);
            $this->success("更新成功");
        } else {
            $info = DB::name('logistics')->where('id', $id)->find();
            $this->assign("info", $info);
            return $this->fetch('edit');
        }
    }

    /**
     * 更新公司物流状态
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updateCompanyType()
    {
        $type = ipost('type');
        $id = ipost('id');
        $where['pid'] = $id;
        $where['raw'] = 2;
        $res = DB::name('logistics')->where($where)->find();
        if (checkArr($res)) {
            Db::name('logistics')->where($where)->update(['status' => $type]);
        } else {
            $info = DB::name('logistics')->where('id', $id)->find();
            $info['pid'] = $id;
            $info['raw'] = 2;
            $info['timestamp'] = time();
            $info['status'] = $type;
            unset($info['id']);

            DB::name('logistics')->insert($info);
        }
        $this->success('更新成功');
    }

    /**
     * 删除物流
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delect()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $ids = join(",", $data['id']);
            $where = "id in (" . $ids . ") OR pid in (" . $ids . ")";
            $where1 = "logistics_id in (" . $ids . ")";
        } else {
            $where = "id =" . $data['id'] . " OR pid=" . $data['id'];
            $where1 = "logistics_id =" . $data['id'];
        }
        Db::name('logistics')->where($where)->delete();
        Db::name('logistics_ship')->where($where1)->delete();
        Db::name('logistics_params')->where($where1)->delete();
        $this->success("删除成功");
    }

    /**************************************************/

    /**
     * 参数设置
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function params($id)
    {
        if (post()) {
            $data = post();
            //检测是否存在
            $where['logistics_id'] = $data['id'];
            $res = DB::name('logistics_params')->where($where)->find();
            if (checkArr($res)) {
                unset($data['id']);
                Db::name('logistics_params')->where($where)->update($data);
            } else {
                $data['logistics_id'] = $data['id'];
                unset($data['id']);
                DB::name('logistics_params')->insert($data);
            }
            $this->success("修改成功");
        } else {
            $where['logistics_id'] = $id;
            $data = Db::name('logistics_params')->where($where)->find();
            $this->assign('info', $data);
            return $this->fetch('params');
        }
    }

    /**
     * 寄件人信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function shipper()
    {
        if (post()) {
            $data = post();
            if ($data['id'] == '') {
                DB::name('company_shipper')->insert($data);
            } else {
                DB::name('company_shipper')->update($data);
            }
            $this->success("更新成功");
        } else {
            $info = DB::name('company_shipper')->find();
            $this->assign("info", $info);
            return $this->fetch('shipper');
        }
    }

    /**
     * 货运方式列表
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function listShip($id)
    {
        sget('short') && $where['short'] = sget('short');
        $where['logistics_id'] = $id;
        $data = Db::name('logistics_ship')
            ->where($where)
            ->order('method_code asc')
            ->paginate(15, false, ['query' =>
                [
                    'id' => iget('id'),
                    'short' => sget('short')
                ]]);
        $this->assign('list', $data);
        $info = DB::name('logistics')->where('id', $id)->find();
        $this->assign("info", $info);
        $this->assign("nation", $this->getDictionary('nation'));
        return $this->fetch('listShip');
    }

    /**
     * 手动物流添加货运方式
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addShip()
    {
        if (post()) {
            $data = post();
            $insertData['logistics_id'] = $data['logistics_id'];
            $insertData['method_code'] = $data['method_code'];
            $insertData['en_name'] = $data['en_name'];
            $insertData['cn_name'] = $data['cn_name'];
            $insertData['deliverytime'] = $data['deliverytime'];
            $insertData['is_weight'] = $data['is_weight'];
            $insertData['type'] = $data['type'];
            DB::name('logistics_ship')->insert($insertData);
            $this->success("添加成功");
        } else {
            $logistics_id = iget('logistics_id');
            $info = DB::name('logistics')->where('id', $logistics_id)->find();
            if (!checkArr($info)) {
                $this->error('当前物流不存在');
            }
            if ($info['manual'] == 2) {
                $this->error('当前物流不支持手动添加货运方式');
            }
            $this->assign("info", $info);
            return $this->fetch('addShip');
        }

    }

    /**
     * 手动物流编辑货运方式
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editShip($id)
    {
        if (post()) {
            $data = post();
            $updateData['method_code'] = $data['method_code'];
            $updateData['en_name'] = $data['en_name'];
            $updateData['cn_name'] = $data['cn_name'];
            $updateData['deliverytime'] = $data['deliverytime'];
            $updateData['is_weight'] = $data['is_weight'];
            $updateData['type'] = $data['type'];
            //检测是否存在
            $where['method_code'] = $data['method_code'];
            $where['logistics_id'] = $data['logistics_id'];
            $where['id'] = ['neq', $data['id']];
            $res = DB::name('logistics_ship')->where($where)->find();
            if (checkArr($res)) {
                $this->error("该货运方式已存在");
            }
            DB::name('logistics_ship')->where('id', $data['id'])->update($updateData);
            $this->success("更新成功");
        } else {
            $info = DB::name('logistics_ship')->where('id', $id)->find();
            $this->assign("info", $info);
            return $this->fetch('editShip');
        }
    }

    /**
     * 更新运输方式状态
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateType()
    {
        $type = post('type');
        $updateData['type'] = $type;
        $where['id'] = post('id');
        $where['logistics_id'] = post('logistics_id');
        Db::name('logistics_ship')->where($where)->update($updateData);
        $this->success('更新成功');
    }

    /**
     * 删除货运方式
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delShip()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where = "id in ('" . join("','", $data['id']) . "')";
        } else {
            $where = "id ='" . $data['id'] . "'";
        }
        $where .= " AND logistics_id=" . $data['logistics_id'];
        Db::name('logistics_ship')->where($where)->delete();
        $this->success('删除成功');
    }

    /**
     * 批量禁用货运方式
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbiddenShip()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where = "id in ('" . join("','", $data['id']) . "')";
        } else {
            $where = "id ='" . $data['id'] . "'";
        }
        $where .= " AND logistics_id=" . $data['logistics_id'];
        Db::name('logistics_ship')->where($where)->update(['type' => 2]);
        $this->success('禁用成功');
    }

    /**************************************************/

    /**
     * 初始化货运方式
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function restore(){
        $id = ipost('id');
        $nid = spost('nid');
        $fun = spost('fun');
        $data = $this->chenkLogistic($id,$nid);
        $nations  =$data['nation'];
        $params  =$data['params'];
        $this->$fun($id,$nations,$params);
    }

    /**
     * 检测国家，参数
     * @param string $id
     * @param string $nid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function chenkLogistic($id='',$nid=''){
        $nations = DB::name('nation')->where('id', $nid)->find();

        if (!checkArr($nations)) {
            $this->error('当前物流暂不支持当前国家');
        }
        //获取物流参数
        $where['logistics_id'] = $id;
        $params = Db::name('logistics_params')->where($where)->find();
        if (!checkArr($params)) {
            $this->error('当前物流暂未配置参数');
        }
        return ['nation'=>$nations,'params'=>$params];
    }

    /**
     * 更新sfc货运列表基础数据
     * @param string $id
     * @param array $nations
     * @param array $params
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateSfc($id='',$nations=[],$params=[])
    {
        if (!checkArr($params)) {
            $this->error('当前物流暂未配置参数');
        }
        if (empty($params['user'])) {
            $this->error('当前物流暂未配置账号id');
        }
        if (empty($params['app_key'])) {
            $this->error('当前物流暂未配置App Key');
        }
        if (empty($params['token'])) {
            $this->error('当前物流暂未配置Token');
        }

        //获取运费
        libxml_disable_entity_loader(false);
        $client = new \SoapClient('http://www.sendfromchina.com/ishipsvc/web-service?wsdl');
        $parameter = array(
            'HeaderRequest' => array(
                'appKey' => $params['app_key'],
                'token' => $params['token'],
                'userId' => $params['user']
            ),
            'ratesRequestInfo' => array(
                'country' => $nations['sfc'],
                'weight' => 1,//单位以 KG 计算。
                'priceType' => 1, //用户为userId的运费信息
            ),
        );
        $resultFee = $client->getRates($parameter);
        $rates = $resultFee->rates;
        if (!checkArr($rates)) {
            $this->error('当前物流暂不支持当前国家');
        }

        foreach ($rates as $value) {
            $insertData[] = array(
                'logistics_id' => $id,
                'method_code' => $value->shiptypecode,
                'en_name' => $value->shiptypename,
                'cn_name' => $value->shiptypecnname,
                'deliverytime' => $value->deliverytime,
                'iftracking' => $value->iftracking == 'YES' ? 1 : 2,
                'is_weight' => $value->isweight == 'YES' ? 1 : 2,
                'type' => 1,
                'short'=>$nations['short'],
                'nation'=>$nations['name']
            );
        }
        $where['logistics_id'] = $id;
        $where['short'] = $nations['short'];
        Db::name('logistics_ship')->where($where)->delete();
        Db::name('logistics_ship')->insertAll($insertData);
        $this->success('初始化成功');
    }

    /**
     * 更新一起飞货运列表
     * @param string $id
     * @param array $nations
     * @param array $params
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updatefeia($id='',$nations=[],$params=[])
    {
        if (!checkArr($params)) {
            $this->error('当前物流暂未配置参数');
        }
        if (empty($params['app_name'])) {
            $this->error('当前物流暂未配置App Name');
        }
        if (empty($params['token'])) {
            $this->error('当前物流暂未配置API Token');
        }

        $url = "http://api.17feia.com/eship-api/v1/products";
        $curlPost = json_encode(array('apiName' => $params['app_name'], 'apiToken' => $params['token']));
        $header = array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($curlPost)
        );
        $con = json_decode(request_post($url, $curlPost, $header), true);

        if ($con['flag'] == false) {
            $this->error($con['msg']);
        }

        if (!checkArr($con['productInfos'])) {
            $this->error('当前物流暂不支持当前国家');
        }

        $insertData = [];
        foreach ($con['productInfos'] as $value) {
            if(in_array($nations['short'], $value['countryCodes'])){
                $insertData[] = array(
                    'logistics_id' => $id,
                    'method_code' => $value['productCode'],
                    'en_name' => $value['productCode'],
                    'cn_name' => $value['productName'],
                    'type' => 1,
                    'short'=>$nations['short'],
                    'nation'=>$nations['name']
                );
            }
        }

        if (!checkArr($insertData)) {
            $this->error('当前物流暂不支持当前国家');
        }
        $where['logistics_id'] = $id;
        $where['short'] = $nations['short'];
        Db::name('logistics_ship')->where($where)->delete();
        Db::name('logistics_ship')->insertAll($insertData);
        $this->success('初始化成功');
    }

    /**
     * 更新云途货运列表
     * @param string $id
     * @param array $nations
     * @param array $params
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateYexpress($id='',$nations=[],$params=[])
    {
        if (!checkArr($params)) {
            $this->error('当前物流暂未配置参数');
        }
        if (empty($params['user'])) {
            $this->error('当前物流暂未配置账号id');
        }
        if (empty($params['secret_key'])) {
            $this->error('当前物流暂未配置Secret Key');
        }

        $url = "http://api.yunexpress.com/LMS.API/api/lms/Get?countryCode=".$nations['short'];
        $header[] = 'Authorization:Basic ' . base64_encode($params['user'].'&'.$params['secret_key']);
        $con = json_decode(request_get($url, $header), true);
        if (!isset($con['Item'])) {
            $this->error($con['ResultDesc']);
        }
        foreach ($con['Item'] as $value) {
            $insertData[] = array(
                'logistics_id' => $id,
                'method_code' => $value['Code'],
                'en_name' => $value['EnglishName'],
                'cn_name' => $value['FullName'],
                'iftracking' => $value['HaveTrackingNum'] == true ? 1 : 2,
                'type' => 1,
                'short'=>$nations['short'],
                'nation'=>$nations['name']
            );
        }
        $where['logistics_id'] = $id;
        $where['short'] = $nations['short'];
        Db::name('logistics_ship')->where($where)->delete();
        Db::name('logistics_ship')->insertAll($insertData);
        $this->success('初始化成功');
    }
}